#-*- coding=utf-8 -*-
import os
import sys
import argparse

from source.util.ConfigUtil import ConfigIni
from source.util.CheckEnvironment import check_environment
from source.core.run import run_device
from source.util.LogUtil import Log,log
from source.util.CommonUtil import getProjectDir

current_path=os.path.split(os.path.realpath(sys.argv[0]))[0]
current_path=current_path.replace('\\','/')

@log()
def init_data_info():

    ini=ConfigIni()

    str=current_path+'/TestCase'
    # print(str)
    ini.set_ini('test_case','case',str)

    ini.set_ini('test_case','log_file',current_path+'/TestResult')

    ini.set_ini('test_case','error_img',current_path+'/config/error.png')

    ini.set_ini('test_device','device',current_path+'/config/device_info.yaml')

    ini.set_ini('test_db','test_result',current_path+'/config/test.db')

@log()
def start(file_list,num):
    Log().info("start......")
    check_environment()
    init_data_info()
    run_device(file_list,num)
    Log().info("end......")
    os._exit(0)
    pass

parser = argparse.ArgumentParser(description='Process some integers.')  # 首先创建一个ArgumentParser对象
# parser.add_argument('integers', metavar='N', type=int, nargs='+',  # 添加参数
#                     help='an integer for the accumulator')
# parser.add_argument('--sum', dest='accumulate', action='store_const',
#                     const=sum, default=max,
#                     help='sum the integers (default: find the max)')  # 添加--sum则返回所有数之和，否则返回列表中的最大值
#argparse 使用  https://www.cnblogs.com/lindaxin/p/7975697.html
parser.add_argument('-f', metavar="file",type=str,nargs='+', help='this file must be place in TestCase folder , then the file will be execute ')
parser.add_argument('--f', metavar="file",type=str,nargs='+', help='this file must be place in TestCase folder , then the file will be execute ')
parser.add_argument('-d', metavar="DIR",type=str, help='a dir must be place in TestCase folder , will be execute ')
parser.add_argument('--d', metavar='DIR', type=str,help='a dir must be place in TestCase folder ,will be execute ')
parser.add_argument('-n', metavar='num', type=int,help='number of executions') #执行次数

def parse_args():
    file_list = []
    args = parser.parse_args()
    if args.f:
        for i,file in enumerate(args.f):
            if isinstance(file,str) and file.endswith("yaml"):
                # 判断脚本是否为指定格式,并组装为[{case_name:"",case_path:""}]格式
                file_list.append((file,getProjectDir()+"/TestCase/"+file))
                pass
    elif args.d:
        print(args.d)
        dir=getProjectDir() + "/TestCase/" + args.d
        if isinstance(args.d[0], str) and os.path.isdir(dir):
            file_list.append(dir)
        else:
            print("the path is not correct")
            return

    num=1
    if args.n:
       num=args.n
    # 判断传入是否为目录
    start(file_list,num)
    pass

if __name__ == '__main__':
    parse_args()
    pass